package com.nineclock.attendance.task;

import cn.hutool.core.collection.CollectionUtil;
import com.nineclock.attendance.dto.AttendPunchDTO;
import com.nineclock.attendance.mapper.AttendGroupMapper;
import com.nineclock.attendance.pojo.AttendGroup;
import com.nineclock.attendance.service.AttendPunchService;
import com.nineclock.common.utils.DateTimeUtil;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Component
@Slf4j
public class SendAttendMailTask {

    @Autowired
    AttendGroupMapper attendGroupMapper;

    @Autowired
    SysUserFeign userFeign;

    @Autowired
    AttendPunchService attendPunchService;

    /**
     * 发送邮件 的任务定义
     *  每个月的"月底" 给 所有的"管理员" 发送一封 该月 的"所有员工"的考勤邮件
     */
    @XxlJob("countAttendanceAndSendMail")
    public void countAttendanceAndSendMail() throws MessagingException {
        //获取每个企业的管理员id
        //查询所有的考勤组信息
        List<AttendGroup> groupList = attendGroupMapper.selectList(null);
        Set<Long> companyIds = groupList.stream().map(attendGroup -> {
            return attendGroup.getCompanyId();
        }).collect(Collectors.toSet());


        //获取 该月 1号 和最后一天的日期， 获取 日期列表
        String currentMonthFirstDay = DateTimeUtil.getCurrentMonthFirstDay();
        String currentMonthLastDay = DateTimeUtil.getCurrentMonthLastDay();
        List<Date> dateList = DateTimeUtil.getDatesBetweenTwoDate(currentMonthFirstDay, currentMonthLastDay, "yyyy-MM-dd");
        List<String> dateStrList = dateList.stream().map(date -> {
            return DateTimeUtil.dateToStr(date, "yyyy-MM-dd");
        }).collect(Collectors.toList());

        if(CollectionUtil.isNotEmpty(companyIds)){
            //循环每一个企业
            for (Long companyId : companyIds) {
                //获取对应企业的员工列表
                List<SysCompanyUserDTO> companyUserDTOList = userFeign.queryCompanyUser(companyId, null).getData();


                //获取考勤列表数据
                List<AttendPunchDTO> attendPunchDTOList = attendPunchService.getAttendPunch(companyId, companyUserDTOList, currentMonthFirstDay, currentMonthLastDay, dateStrList);

                //生成 考勤列表的excel文件, 获取文件的地址
                String path = attendPunchService.generateExcelReport(companyId ,attendPunchDTOList ,currentMonthFirstDay );

                // 获取企业管理员的邮箱地址，发送考勤邮件
                SysCompanyUserDTO userDTO = userFeign.queryAdminByCompanyId(companyId).getData();
                String email = userDTO.getEmail();

                this.sendMail(email, path);
            }
        }




    }


    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private JavaMailSender javaMailSender;

    public void sendMail(String toEmail , String path) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        //用哪个邮箱发出邮件
        mimeMessageHelper.setFrom(from);
        // 设置目标邮箱
        mimeMessageHelper.setTo(toEmail);
        //设置抄送邮箱
        mimeMessageHelper.setCc(new String[]{"hz24107@163.com", "sunliang@itcast.cn"});

        mimeMessageHelper.setText("这是一封测试考勤邮件");
        mimeMessageHelper.setSubject("测试考勤发送邮件");

        mimeMessageHelper.setText("测试邮件，请不要恢复，随时删除!!");
        // 添加附件
        mimeMessageHelper.addAttachment("考勤右键", new File(path));

        javaMailSender.send(mimeMessage);

    }




}
